package com.cwits.wifi.ui.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

import com.cwits.wifi.MainApplication;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.manager.MConstant;
import com.cwits.wifi.manager.SocketConnectListener;
import com.cwits.wifi.manager.SocketReceiveCallback;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.IConstant;
import com.cwits.wifi.util.PreferencesHelper;
import com.jieli.lib.dv.control.json.bean.NotifyInfo;
import com.jieli.lib.stream.beans.StateInfo;
import com.jieli.lib.stream.tools.ParseHelper;
import com.jieli.lib.stream.util.ICommon;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

public class CommunicationService extends Service implements ICommon, IAction, IConstant,MConstant, SocketConnectListener, SocketReceiveCallback {
    private final String tag = getClass().getSimpleName();
    private boolean isStopPowerRunning = true;
    //private CommandHub mCommandHub;
    private final static HashMap<String, String> mDeviceStatus = new HashMap<>();
    private static CommunicationService instance = null;
    private static boolean isUsbMode = false;
    private final Handler mHandler = new Handler();
    private boolean isRequest = false;
    private boolean isEncryption = false;
    private static boolean isInit = false;
    private static boolean isInitService = false;
    private static String deviceIP;
    private static int modeState = MODE_STATE_168;//50001正常模式，50002富媒体模式

    public static CommunicationService getInstance(){
        if (instance == null){
            instance = new CommunicationService();
            isInit = false;
        }
        return instance;
    }

    public static boolean getIsInitService(){
        return isInitService;
    }
    public static void setDeviceIP(String ip){
        deviceIP = ip;
    }
    public static void setModeState(int state){
        modeState = state;
    }

    private static OnUsbModeListener mOnUsbModeListener;
    public void setOnUsbModeListener(OnUsbModeListener listener){
        Dbug.e(tag, "mOnUsbModeListener:" + mOnUsbModeListener);
        mOnUsbModeListener = listener;
    }

    @Override
    public void onSocketStatusChanged(Integer status) {
        switch (status){
            case SOCKET_STATUS_CONNECTED:
                //mCommandManager.clearDeviceStatus();
                Intent intent = new Intent(ACTION_INIT_CTP_SOCKET_SUCCESS);
                sendBroadcast(intent);
                break;
            case SOCKET_STATUS_CONNECTING:
                break;
            case SOCKET_STATUS_DISCONNECTED:
                break;
            case SOCKET_STATUS_CONNECTION_TIMEOUT:
            case SOCKET_STATUS_EXCEPTION:
            case SOCKET_STATUS_NO_168DVRCAR:
                Intent intent2 = new Intent(ACTION_DEVICE_CONNECTION_ERROR);
                intent2.putExtra(KEY_DEVICE_CONNECTION_ERROR, 1);
                sendBroadcast(intent2);
                break;
        }
    }

    public interface OnUsbModeListener{
        void onCancel();
        void onShow();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        /*Establish socket*/
        isInitService = true;
        isInit = false;
        //mCommandHub = CommandHub.getInstance();
        Dbug.i("CommunicationService", "----------onCreate---------");
        /*Start power thread*/
//        PowerThread thread = new PowerThread();
//        thread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Dbug.i("CommunicationService", "----------onStartCommand---------");
        if (intent == null){
            return START_STICKY;
        }
        int cmd = intent.getIntExtra(IConstant.SERVICE_CMD, -1);
        Dbug.d(tag, "onStartCommand==========cmd=" + cmd);
        switch (cmd){
            case IConstant.SERVICE_CMD_INIT_SOCKET:
                if(!isInit){
                    /*
                    if(modeState == MODE_STATE_RM){
                        mCommandHub.createClient(deviceIP,AP_MODE_DEVICE_PORT);
                    }else{
                        mCommandHub.createClient();
                    }
                    */
                    if(deviceIP == null||deviceIP.equals(""))
                        deviceIP = "192.168.1.1";
                    ControlManager.getInstance().connectSocket(deviceIP);

                    ControlManager.getInstance().registerSocketConnectListener(this);
                    ControlManager.getInstance().registerSocketReceiveCallback(this);
                }{
                ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_DEVICE_LANGUAGE);
            }
//                mCommandHub.requestStatus(ICommon.CTP_ID_DEFAULT, ICommon.CMD_DEVICE_VERSION);
                break;
            case IConstant.SERVICE_CMD_CLOSE_SOCKET:
                closeSocket();
                break;
        }
        return START_STICKY;
    }

    private void closeSocket(){
        mDeviceStatus.clear();
        ControlManager.getInstance().disconnectSocket();
        modeState = MODE_STATE_168;
        isInit = false;
    }

    public String getDeviceStatus(String cmdNumber){
        Dbug.w(tag, "get cmdNumber:" + cmdNumber);
        return mDeviceStatus.get(cmdNumber);
    }

    @Override
    public void onDestroy() {
        Dbug.w(tag, "onDestroy=============");
        release();
        isInitService = false;
        modeState = MODE_STATE_168;
        super.onDestroy();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Dbug.w(tag, "onTaskRemoved=============");
        release();
        stopSelf();
        super.onTaskRemoved(rootIntent);
    }

    private void release(){
        ControlManager.getInstance().sendCommand(CTP_ID_DEFAULT, CMD_DISABLE_DEVICE_WIFI, ARGS_DISABLE_DEVICE_WIFI);
        //mCommandHub.closeClient();
        ControlManager.getInstance().unregisterSocketConnectListener(this);
        ControlManager.getInstance().unregisterSocketReceiveCallback(this);
        mHandler.removeCallbacksAndMessages(null);
        isStopPowerRunning = false;
        mDeviceStatus.clear();
        isInit = false;
        modeState = MODE_STATE_168;
    }

    /*
    @Override
    public void onConnected() {
        Intent intent = new Intent(ACTION_INIT_CTP_SOCKET_SUCCESS);
        sendBroadcast(intent);
    }

    @Override
    public void onError(int errorType) {
        Intent intent = new Intent(ACTION_DEVICE_CONNECTION_ERROR);
        intent.putExtra(KEY_DEVICE_CONNECTION_ERROR, errorType);
        sendBroadcast(intent);
    }
    */

    @Override
    public void onReceive(StateInfo stateInfo) {
        Dbug.i(tag, "put cmdNumber:" + stateInfo.getCmdNumber() + ", id=" + stateInfo.getParam()[0]);
        mDeviceStatus.put(stateInfo.getCmdNumber(), stateInfo.getParam()[0]);

        switch (stateInfo.getCmdNumber()){
            case CMD_START_RECORD:
                String s = stateInfo.getParam()[0];
                mDeviceStatus.put(CMD_GET_RECORDING_STATUS, stateInfo.getParam()[0]);
                break;
            case CMD_STOP_RECORD:
                mDeviceStatus.put(CMD_GET_RECORDING_STATUS, stateInfo.getParam()[0]);
                break;
            case CMD_DEVICE_WIFI_DISABLED:
                Intent deviceWifiIntent = new Intent(IAction.ACTION_DEVICE_WIFI_DISABLED);
                sendBroadcast(deviceWifiIntent);
                isInit = false;
                modeState = MODE_STATE_168;
                return;
            case CMD_DEVICE_MODE:
                Dbug.d(tag, "mOnUsbModeListener:" + mOnUsbModeListener);
                if (ARGS_USB_MODE.equals(stateInfo.getParam()[0])){
                    if (mOnUsbModeListener != null){
                        mOnUsbModeListener.onShow();
                    }
                    isUsbMode = true;
                } else {
                    if (isUsbMode){
                        isUsbMode = false;
                        if (mOnUsbModeListener != null){
                            mOnUsbModeListener.onCancel();
                        }
                    }
                }
                break;
        }

        switch (stateInfo.getCmdNumber()) {
            case CMD_SDCARD_STATE:
                Intent sdcardIntent = new Intent(IAction.ACTION_SDCARD_STATE);
                sdcardIntent.putExtra(KEY_SDCARD_STATE, stateInfo);
                sendBroadcast(sdcardIntent);
                break;
            case CMD_APP_REQUEST_CONNECTION:
                if (ARGS_DEVICE_HAS_TAKEN.equals(stateInfo.getParam()[0]) || ARGS_DEVICE_IN_USB_MODE.equals(stateInfo.getParam()[0])){
                    Intent requestConnection = new Intent(IAction.ACTION_REJECT_CONNECTION);
                    requestConnection.putExtra(KEY_REJECT_CONNECTION, stateInfo.getParam()[0]);
                    sendBroadcast(requestConnection);
                    isInit = false;
                } else if (ARGS_ACCEPT_CONNECTION.equals(stateInfo.getParam()[0])){
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_SNAPSHOT);
                    isEncryption = false;
                    isRequest = false;
                    Dbug.i(tag, "check the encryption");
                    ControlManager.getInstance().sendCommand("0002", "0598", "0000");
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(!isEncryption){
                                //秘密失败
                                isRequest = true;
                                Intent encryption_error = new Intent(IAction.ACTION_GET_ENCRYPTION_ERROR);
                                sendBroadcast(encryption_error);
                            }

                        }
                    },7000);
                }
                break;
            case CMD_DEVICE_UUID:
//                Dbug.i(tag, "stateInfo.getContent():"+stateInfo.getParam()[1]);
                MainApplication.getApplication().setDeviceUUID(stateInfo.getParam()[1]);
                break;
            /*
            case CMD_DEVICE_VERSION:
//                Dbug.d(tag, "CMD_DEVICE_VERSION:"+stateInfo.getParam()[1]);
                String versionInfo = stateInfo.getParam()[1];
                if(versionInfo != null && !versionInfo.isEmpty()){
                    SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
                    String saveVersionInfo = sharedPreferences.getString(DEVICE_VERSION_INFO, null);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    if(saveVersionInfo == null){
                        editor.putString(DEVICE_VERSION_INFO, versionInfo);
                        editor.commit();
                    }else{
                        if(!saveVersionInfo.equals(versionInfo)){
                            editor.remove(DEVICE_VERSION_INFO);
                            editor.putString(DEVICE_VERSION_INFO, versionInfo);
                            editor.commit();
                        }
                    }
//                    MainApplication.getApplication().setDeviceVersion(stateInfo.getParam()[1]);
                }
                mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_DEVICE_LANGUAGE);
                Dbug.d(tag, "requestStatus CMD_DEVICE_LANGUAGE over.");
                break;
            */
            case CMD_DEVICE_LANGUAGE:
//                Dbug.d(tag, "CMD_DEVICE_LANGUAGE: lang code=" + stateInfo.getContentID() + ", lang UI="+ stateInfo.getContent());
                if(isInit){
                    //初始化成功
                    Dbug.i(tag, "CMD_DEVICE_LANGUAGE:change language");
                }else{
                    isInit = true;
                    Intent requestIntent = new Intent(IAction.ACTION_REQUEST_UI_DESCRIPTION);
                    requestIntent.putExtra(KEY_REQUEST_UI_DESCRIPTION, stateInfo);
                    sendBroadcast(requestIntent);

                    /**Sync device's date*/
                    //eg: 2015 01 02 12 12 12
                    String dateParam = formatDateSplitSpace(new Date());
                    Dbug.i(tag, "CMD_DEVICE_DATE============dateParam:" + dateParam);
                    ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, CMD_DEVICE_DATE, dateParam);

                    /**Sync device's battery*/
                    //mCommandHub.requestStatus(CTP_ID_DEFAULT, CMD_BATTERY_STATE);
                }

                break;
            case CMD_FIRMWARE_UPGRADE:
                Intent intent = new Intent(IAction.ACTION_ALLOW_FIRMWARE_UPGRADE);
                intent.putExtra(KEY_SDCARD_STATE, stateInfo);
                sendBroadcast(intent);
                break;
            case CMD_AP_SSID:
                String ssid = stateInfo.getParam()[0];
                Dbug.i(tag, "CMD_AP_SSID============ssid:" + ssid);
                if (!TextUtils.isEmpty(ssid)){

                    if (MainApplication.getApplication().isModifySSID()){
                        MainApplication.getApplication().setModifySSID(false);

                        /**Send command to restart*/
                        //mCommandHub.sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_RESTART_DEVICE, ICommon.ARGS_RESTART_DEVICE);

                        //closeSocket();

                        sendBroadcast(new Intent(ACTION_CHANGE_SSID_SUCCESS));

                        SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
                        String currentPWD = sharedPreferences.getString(CURRENT_PWD, null);
                        if (!TextUtils.isEmpty(currentPWD)){
                            MainApplication.getApplication().setLastModifySSID(ssid);
                            PreferencesHelper.putStringValue(MainApplication.getApplication(), ssid, currentPWD);
                        }
                    } else {
                        /**Save device Wi-Fi SSID */
                        PreferencesHelper.putStringValue(MainApplication.getApplication(), CURRENT_SSID, ssid);
                        PreferencesHelper.putStringValue(MainApplication.getApplication(), ssid, null);
                        ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, CMD_AP_PASSWORD, " ");
                    }
                }else{
                    sendBroadcast(new Intent(ACTION_CHANGE_SSID_FAILED));
                }
                break;
            case CMD_AP_PASSWORD:
                String pwd = stateInfo.getParam()[0];

                if (!TextUtils.isEmpty(pwd)){

                    if (MainApplication.getApplication().isModifyPWD()){
                        MainApplication.getApplication().setModifyPWD(false);

                        /**Send command to restart*/
                        //mCommandHub.sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_RESTART_DEVICE, ICommon.ARGS_RESTART_DEVICE);

                        //closeSocket();

                        sendBroadcast(new Intent(ACTION_CHANGE_PWD_SUCCESS));

                        /*String lastSSID = MainApplication.getApplication().getLastModifySSID();
                        if (!TextUtils.isEmpty(lastSSID)){
                            *//**Save for next login *//*
                            SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
                            String newSSID = sharedPreferences.getString(lastSSID, null);
                            if (!TextUtils.isEmpty(newSSID)){

                                PreferencesHelper.putStringValue(MainApplication.getApplication(), newSSID, pwd);
                            } else {
                                *//**Save device Wi-Fi password *//*
                                PreferencesHelper.putStringValue(MainApplication.getApplication(), CURRENT_PWD, pwd);
                            }
                        }*/
                    } else {
                        SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
                        String currSSID = sharedPreferences.getString(CURRENT_SSID, null);
                        if (!TextUtils.isEmpty(currSSID)){

                            if (ARGS_AP_PWD_NONE.equals(pwd)){
                                PreferencesHelper.putStringValue(MainApplication.getApplication(), CURRENT_PWD, "");
                                PreferencesHelper.putStringValue(MainApplication.getApplication(), currSSID, "");
                            } else {
                                PreferencesHelper.putStringValue(MainApplication.getApplication(), currSSID, pwd);
                                PreferencesHelper.putStringValue(MainApplication.getApplication(), CURRENT_PWD, pwd);
                            }
                        }
                    }
                }else{
                    sendBroadcast(new Intent(ACTION_CHANGE_PWD_FAILED));
                }
                break;
            case CMD_FORMAT_SDCARD:
                sendBroadcast(new Intent(IAction.ACTION_FORMAT_SDCARD));
                break;
            case CMD_RESET_DEVICE:
                mDeviceStatus.clear();
                sendBroadcast(new Intent(IAction.ACTION_RESET_DEVICE));
                break;
            case CMD_ALL_VIDEO_DESC_NAME:
            case CMD_REAR_ALL_VIDEOS_INFO:

                String state = stateInfo.getParam()[0];
                if(ARGS_ALL_VIDEO_DESC_NAME_SUCCESS.equals(state)) {
                    final String videoListFileName = stateInfo.getParam()[1];

                    ParseHelper.getInstance().requestVideoInfoText(getApplicationContext(), videoListFileName, new ParseHelper.ResponseListener() {
                        @Override
                        public void onResponse(boolean isSuccess) {
                            if (isSuccess) {
                                //Dbug.w(tag, "Request " + videoListFileName + " success!!");
                                Intent videoFileName = new Intent(IAction.ACTION_RESPONDING_VIDEO_DESC_REQUEST);
                                sendBroadcast(videoFileName);
                            } else {
                                Dbug.e(tag, "Request " + videoListFileName + " fail!");
                            }
                        }
                    });
                }

                /*
                String state = stateInfo.getParam()[0];
                if(ARGS_ALL_VIDEO_DESC_NAME_SUCCESS.equals(state)) {
                    final String videoListFileName = stateInfo.getParam()[1];
                    if(!TextUtils.isEmpty(videoListFileName)){
                        new VideoInfoTxtAndCaptureTxt(getApplicationContext(), videoListFileName, MainApplication.getApplication().getCaptureSize()).start();
                    }
                }
                */
                break;
            case CMD_GET_VIDEO_THUMBNAIL:
                sendBroadcast(new Intent(IAction.ACTION_REQUEST_THUMBNAIL));
                break;
            case CMD_DISABLE_DEVICE_WIFI:
                Intent closeDevWifi = new Intent(IAction.ACTION_CLOSE_DEV_WIFI);
                closeDevWifi.putExtra(CLOSE_DEV_WIFI, stateInfo);
                sendBroadcast(closeDevWifi);
                break;
            case CMD_VIDEO_STOP:
                sendBroadcast(new Intent(ACTION_PLAYBACK_STATE_STOP));
                break;
            //case CMD_VIDEO_PAUSE:
             //   sendBroadcast(new Intent(ACTION_PLAYBACK_STATE_PAUSE));
              //  break;
           // case CMD_VIDEO_PLAY:
             //   Intent special = new Intent(IAction.ACTION_SPECIAL_DATA);
           //     special.putExtra(KEY_SPECIAL_STATE, stateInfo);
            //    sendBroadcast(special);
            //    break;
            case CMD_SNAPSHOT:
                String param1 = stateInfo.getParam()[0];
                if(stateInfo.getParam().length >= 1){
                    int captureSize = Integer.valueOf(param1);
                    MainApplication.getApplication().setCaptureSize(captureSize);
                }
                break;
            case "2000":
                Intent sdcardIntent1 = new Intent(IAction.ACTION_GET_VIDEO_SIZE_STATUS);
                sdcardIntent1.putExtra(KEY_GET_VIDEO_SIZE_STATUS, stateInfo);
                sendBroadcast(sdcardIntent1);
                break;

            case CMD_GET_RECORDING_STATUS:
                Intent get_recording_special = new Intent(IAction.ACTION_GET_RECORDING_STATUS);
                get_recording_special.putExtra(KEY_GET_RECORDING_STATUS, stateInfo);
                sendBroadcast(get_recording_special);
                mDeviceStatus.put(CMD_GET_RECORDING_STATUS, stateInfo.getParam()[0]);
                break;
            case CMD_CONTROL_RTS_VOICE:
                Intent special = new Intent(IAction.ACTION_SPECIAL_DATA);
                special.putExtra(KEY_SPECIAL_STATE, stateInfo);
                sendBroadcast(special);
                break;
            case CMD_RT_STREAM_OPEN:
                Intent special1 = new Intent(IAction.ACTION_SPECIAL_DATA);
                special1.putExtra(KEY_SPECIAL_STATE, stateInfo);
                sendBroadcast(special1);
                break;
            case CMD_REAR_CAMERA_PLUG_STATE:
                Intent plugStateIntent = new Intent(IAction.ACTION_REAR_CAMERA_PLUG_STATE);
                plugStateIntent.putExtra(KEY_REAR_CAMERA_PLUG_STATE, stateInfo);
                sendBroadcast(plugStateIntent);
                break;
            case CMD_REVERSING_STATE:
                Intent reversingIntent = new Intent(IAction.ACTION_REVERSING_STATE);
                reversingIntent.putExtra(KEY_REVERSING_STATE, stateInfo);
                sendBroadcast(reversingIntent);
                //倒车信号开启
                break;
            //case CMD_VIDEO_PLAYBACK_END:
            case CMD_DEVICE_MODE:
            case CMD_SP_SSID:
            case CMD_SP_PASSWORD:
            case CMD_PHOTO_STATE:
            case CMD_BATTERY_STATE:
            case CMD_TAKE_PHOTO:
            case CMD_START_RECORD:
            case CMD_STOP_RECORD:
            case CMD_TIMER_PICTURE:
            case CMD_DELETE_FILE:
            case CMD_DELETE_ALL:
            case CMD_VIDEO_PICTURE_QUALITY:
            case CMD_PHOTO_SIZE:
            case CMD_CONTINUOUS_SHOOTING:
            //case CMD_VIDEO_SIZE:
            case CMD_METERING:
            case CMD_TIMER_PICTURE_STATUS:
            case CMD_ENTER_BROWSING_MODE:
            case CMD_EXIT_BROWSING_MODE:
            case CMD_DEVICE_DATE:
            case CMD_VIDEO_START_PLAYBACK:
            case CMD_REAR_VIDEO_PLAYBACK_START:
            case CMD_REAR_VIDEO_PLAYBACK_STOP:
            case CMD_REAR_RTS_OPEN:
            case CMD_REAR_RTS_CLOSE:
            //case CMD_SLOWDOWN:
            //case CMD_ACCELERATION:
            //case CMD_VIDEO_FILE_END:
            //    Intent videoIntent = new Intent(ACTION_VIDEO_FILE_END);
            //    videoIntent.putExtra(KEY_VIDEO_FILE_END, stateInfo.getParam()[0]);
            //    sendBroadcast(videoIntent);
            //    break;
            case CMD_RT_STREAM_CLOSE:
                Intent special2 = new Intent(IAction.ACTION_SPECIAL_DATA);
                special2.putExtra(KEY_SPECIAL_STATE, stateInfo);
                sendBroadcast(special2);
                break;
            case CMD_WHITE_BALANCE:
                Intent white_balance_info = new Intent(IAction.ACTION_GET_WHITE_BALANCE_STATUS);
                white_balance_info.putExtra(KEY_GET_WHITE_BALANCE__STATUS, stateInfo);
                sendBroadcast(white_balance_info);
                break;
            case "0550":
                Intent versio_info = new Intent(IAction.ACTION_GET_VERSION_INFO);
                versio_info.putExtra(KEY_GET_VERSION_INFO, stateInfo);
                sendBroadcast(versio_info);
                break;
            case "0551":
                Intent device_info = new Intent(IAction.ACTION_GET_DEVICE_INFO);
                device_info.putExtra(KEY_GETDEVICE_INFO, stateInfo);
                sendBroadcast(device_info);
                break;
            case "0552":
                Intent set_sos_info = new Intent(IAction.ACTION_SET_SOSSTORAGE_INFO);
                set_sos_info.putExtra(KEY_SETSOSSTORAGE_INFO, stateInfo);
                sendBroadcast(set_sos_info);
                break;
            case "0553":
                Intent sos_info = new Intent(IAction.ACTION_GET_SOSSTORAGE_INFO);
                sos_info.putExtra(KEY_GETSOSSTORAGE_INFO, stateInfo);
                sendBroadcast(sos_info);
                break;
            case "0554":
                Intent sos_release_info = new Intent(IAction.ACTION_RELEASE_SOSSTORAGE_INFO);
                sos_release_info.putExtra(KEY_RELEASESOSSTORAGE_INFO, stateInfo);
                sendBroadcast(sos_release_info);
                break;
            case "3101":
                Intent recording_voice_info = new Intent(IAction.ACTION_GET_RECORDING_VOICE_STATUS);
                recording_voice_info.putExtra(KEY_GET_RECORDING_VOICE_STATUS, stateInfo);
                sendBroadcast(recording_voice_info);
                break;
            case "2008":
                Intent shake_info = new Intent(IAction.ACTION_GET_SOS_SHAKE_STATUS);
                shake_info.putExtra(KEY_GET_SOS_SHAKE_STATUS, stateInfo);
                sendBroadcast(shake_info);
                break;
            case "2009":
                Intent heavry_info = new Intent(IAction.ACTION_GET_HEAVRY_STATUS);
                heavry_info.putExtra(KEY_GET_HEAVRY__STATUS, stateInfo);
                sendBroadcast(heavry_info);
                break;
            case "2002":
                //循环录影
                Intent looprecord_info = new Intent(IAction.ACTION_GET_LOOPRECORD_STATUS);
                looprecord_info.putExtra(KEY_GET_LOOPRECORD__STATUS, stateInfo);
                sendBroadcast(looprecord_info);
                break;
            case "3010":
                //运动检测
                Intent detect_dv_info = new Intent(IAction.ACTION_GET_DETECTDV_STATUS);
                detect_dv_info.putExtra(KEY_GET_DETECTDV__STATUS, stateInfo);
                sendBroadcast(detect_dv_info);
                break;
            case "3100":
                //按键声音
                Intent deep_voice_info = new Intent(IAction.ACTION_GET_DEEPVOICE_STATUS);
                deep_voice_info.putExtra(KEY_GET_DEEPVOICE__STATUS, stateInfo);
                sendBroadcast(deep_voice_info);
                break;
            case "3001":
                //自动关机
                Intent auto_close_info = new Intent(IAction.ACTION_GET_AUTOCLOSE_STATUS);
                auto_close_info.putExtra(KEY_GET_AUTOCLOSE__STATUS, stateInfo);
                sendBroadcast(auto_close_info);
                break;
            case "3002":
                //屏保
                Intent screen_save_info = new Intent(IAction.ACTION_GET_SCREENSAVE_STATUS);
                screen_save_info.putExtra(KEY_GET_SCREENSAVE__STATUS, stateInfo);
                sendBroadcast(screen_save_info);
                break;
            case "3008":
                //光源
                Intent sunny_info = new Intent(IAction.ACTION_GET_SUNNY_STATUS);
                sunny_info.putExtra(KEY_GET_SUNNY__STATUS, stateInfo);
                sendBroadcast(sunny_info);
                break;
            case "3000":
                //补光
                Intent add_sunny_info = new Intent(IAction.ACTION_GET_ADD_SUNNY_STATUS);
                add_sunny_info.putExtra(KEY_GET_ADD_SUNNY__STATUS, stateInfo);
                sendBroadcast(add_sunny_info);
                break;
            case "3006":
                //语言设置
                Intent langune_info = new Intent(IAction.ACTION_GET_LANGUNE_STATUS);
                langune_info.putExtra(KEY_GET_LANGUNE__STATUS, stateInfo);
                sendBroadcast(langune_info);
                break;
            case "0598":
                ControlManager.getInstance().sendCommand("0002", "0599", "0008", "CHAINWAY");
                break;
            case "0599":
                //加密成功
                if(!isRequest&&isEncryption == false){
                    isEncryption = true;
                    new Thread(getDeviceVersionInfo).start();
                }
                break;
            case "0600":
                String s = stateInfo.getParam()[0];
                Dbug.i(tag,"--------0600----" + stateInfo.toString());
                break;
            default:
//              Dbug.i(tag, "generic=====[" + data + "]");
                Intent currMode = new Intent(IAction.ACTION_GENERIC_DATA);
                currMode.putExtra(KEY_GENERIC_STATE, stateInfo);
                sendBroadcast(currMode);
                ParseHelper.getInstance().updateState(stateInfo.getCmdNumber(), stateInfo.getParam()[0]);
                break;
        }
    }

    @Override
    public void onNotify(NotifyInfo data) {

    }

    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy MM dd HH mm ss", Locale.getDefault());
    private String formatDateSplitSpace(Date date) {
        return sDateFormat.format(date);
    }

    private Runnable getDeviceVersionInfo = new Runnable() {
        @Override
        public void run() {
            isRequest = true;
            ParseHelper.getInstance().requestDeviceVersionText(getApplicationContext(), DEVICE_VERSION_INFO_NAME, new ParseHelper.ResponseListener() {
                @Override
                public void onResponse(boolean isSuccess) {
                    isRequest = false;
                    if (isSuccess) {
                        String deviceVersionMsg = ParseHelper.getInstance().getDeviceVersionMsg();
                        if(!TextUtils.isEmpty(deviceVersionMsg)) {
                            PreferencesHelper.putStringValue(getApplicationContext(), DEVICE_VERSION_MSG, deviceVersionMsg);
                        }
                        ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_DEVICE_LANGUAGE);
                    }else{
                        ParseHelper.getInstance().requestDeviceVersionText(getApplicationContext(), DEVICE_VERSION_INFO_NAME, new ParseHelper.ResponseListener() {
                            @Override
                            public void onResponse(boolean isSuccess) {
                                if(isSuccess){
                                    String deviceVersionMsg = ParseHelper.getInstance().getDeviceVersionMsg();
                                    if(!TextUtils.isEmpty(deviceVersionMsg)){
                                        PreferencesHelper.putStringValue(getApplicationContext(), DEVICE_VERSION_MSG, deviceVersionMsg);
                                    }
                                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_DEVICE_LANGUAGE);
                                }else{
                                    ParseHelper.getInstance().requestDeviceVersionText(getApplicationContext(), DEVICE_VERSION_INFO_NAME, new ParseHelper.ResponseListener() {
                                        @Override
                                        public void onResponse(boolean isSuccess) {
                                            if(isSuccess){
                                                String deviceVersionMsg = ParseHelper.getInstance().getDeviceVersionMsg();
                                                if(!TextUtils.isEmpty(deviceVersionMsg)){
                                                    PreferencesHelper.putStringValue(getApplicationContext(), DEVICE_VERSION_MSG, deviceVersionMsg);
                                                }
                                                ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_DEVICE_LANGUAGE);
                                            }else{
                                                ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_DEVICE_LANGUAGE);
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
    };


    private static class VideoInfoTxtAndCaptureTxt extends Thread{
        private final String tag = this.getClass().getSimpleName();
        private String videoInfoTxtName;
        private int captureSize;
        private WeakReference<Context> mContextWeakReference;

        VideoInfoTxtAndCaptureTxt(Context context, String fileName, int size){
            this.videoInfoTxtName = fileName;
            this.captureSize = size;
            mContextWeakReference = new WeakReference<>(context);
        }

        private void getCaptureTxt(final int size){
            if (mContextWeakReference.get() == null)
                return;
            if(size >= 0){
                ParseHelper.getInstance().requestCaptureText(mContextWeakReference.get(), size, new ParseHelper.ResponseListener() {
                    @Override
                    public void onResponse(boolean isSuccess) {
                        if (mContextWeakReference.get() == null){
                            Dbug.e(tag, "Context is null");
                            return;
                        }
                        if (isSuccess) {
                            Intent videoFileName = new Intent(IAction.ACTION_RESPONDING_VIDEO_DESC_REQUEST);
                            mContextWeakReference.get().sendBroadcast(videoFileName);
                        } else {
                            ParseHelper.getInstance().requestCaptureText(mContextWeakReference.get(), size,  new ParseHelper.ResponseListener() {
                                @Override
                                public void onResponse(boolean isSuccess) {
                                    if (mContextWeakReference.get() == null){
                                        Dbug.e(tag, "Context is null again.");
                                        return;
                                    }
                                    Intent videoFileName = new Intent(IAction.ACTION_RESPONDING_VIDEO_DESC_REQUEST);
                                    mContextWeakReference.get().sendBroadcast(videoFileName);
                                }
                            });
                        }
                    }
                });
            }else{
                Intent videoFileName = new Intent(IAction.ACTION_RESPONDING_VIDEO_DESC_REQUEST);
                mContextWeakReference.get().sendBroadcast(videoFileName);
            }
        }

        @Override
        public void run() {
            if (mContextWeakReference.get() == null)
                return;
            ParseHelper.getInstance().requestVideoInfoText(mContextWeakReference.get(), videoInfoTxtName, new ParseHelper.ResponseListener() {
                @Override
                public void onResponse(boolean isSuccess) {
                    if (isSuccess) {
                        //Dbug.w(tag, "Request " + videoListFileName + " success!!");
                        getCaptureTxt(captureSize);
                    } else {
                        ParseHelper.getInstance().requestVideoInfoText(mContextWeakReference.get(), videoInfoTxtName, new ParseHelper.ResponseListener() {
                            @Override
                            public void onResponse(boolean isSuccess) {
                                if (mContextWeakReference.get() == null){
                                    Dbug.e(tag, "mContextWeakReference is null again.");
                                    return;
                                }
                                if (isSuccess) {
                                    getCaptureTxt(captureSize);
                                } else {
                                    Dbug.e(tag, "Request " + videoInfoTxtName + " fail!");
                                    //mContextWeakReference.get().sendBroadcast(new Intent(IAction.ACTION_GET_VIDEO_INFO_ERROR));
                                }
                            }
                        });
                    }
                }
            });
        }
    }
}
